package fr.aura.launcher.client;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import org.apache.log4j.Logger;

public class LNCSrvCnxMsg  {
	/**
	 * 
	 */
	private static int byteSize=0;
	static Logger logger = Logger.getLogger(LNCSrvCnxMsg.class.getName());
	
	LNCSrvMsgHeader hdr;
	short serverId;
	int nOem;
	byte licence[];
	byte filler[];

	public LNCSrvCnxMsg() {
		hdr = new LNCSrvMsgHeader();
		licence = new byte[10];
		filler = new byte[14];
		byteSize=hdr.getByteSize();
		byteSize+=2+4+10+14;
	}

	public LNCSrvMsgHeader getHdr() {
		return hdr;
	}

	public void setHdr(LNCSrvMsgHeader hdr) {
		this.hdr = hdr;
	}

	public short getServerId() {
		return serverId;
	}

	public void setServerId(short serverId) {
		this.serverId = serverId;
	}

	public int getnOem() {
		return nOem;
	}

	public void setnOem(int nOem) {
		this.nOem = nOem;
	}

	public String getLicence() {
		String returnValue = new String(licence);
		return returnValue;
	}

	public void setLicence(String licence) {
		byte[] tmpLicence = null;
		try {
			tmpLicence = licence.getBytes("ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			logger.error("LNCSrvCnxMsg::setLicence Unable to convert licence to ISO-8859-1");
		}
		if (tmpLicence != null) {
			if (tmpLicence.length > 10) {
				for (int i = 0; i<10; i++) {
					this.licence[i] = tmpLicence[i];
				}
				
			} else {
				this.licence = tmpLicence;
			}
		}
	}

	public String getFiller() {
		String returnValue = new String(filler);
		return returnValue;
	}

	public void setFiller(String filler) {
		byte[] tmpFiller = null;
		try {
			tmpFiller = filler.getBytes("ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			logger.error("LNCSrvCnxMsg::setLicence Unable to convert filler to ISO-8859-1");
		}
		if (tmpFiller != null) {
			if (tmpFiller.length > 14) {
				for (int i = 0; i<14; i++) {
					this.filler[i] = tmpFiller[i];
				}
				
			} else {
				this.filler = tmpFiller;
			}
		}
	}

	public byte[] toByteArray() {
		//default buffer endian order is BIG_ENDIAN, which is fine for network transmission
		ByteBuffer myBuffer = ByteBuffer.allocate(byteSize);
		myBuffer.order(ByteOrder.LITTLE_ENDIAN);
		byte headerBytes[] = this.hdr.toByteArray();
		myBuffer.put(headerBytes).putShort(this.serverId).putInt(this.nOem).put(this.licence).put(this.filler);
		return myBuffer.array();
	}
	
	public void fromByteArray(byte[] byteArray) {
		ByteBuffer myBuffer = ByteBuffer.wrap(byteArray);
		myBuffer.order(ByteOrder.LITTLE_ENDIAN);
		
		this.hdr.fromByteArray(myBuffer);
		this.serverId = myBuffer.getShort();
		this.nOem = myBuffer.getInt();
		myBuffer.get(this.licence,0 , 10);
		myBuffer.get(this.filler, 0, 14);
	}
	
	public int getByteSize() {
		return byteSize;
	}
}
